import type { ButtomImportProps, ButtomImportInstance, UseButtomImportReturnType } from './typing';
import { ref, getCurrentInstance, unref } from 'vue';
import { isProdMode } from '/@/utils/env';

export function useButtomImport(props?: Partial<ButtomImportProps>): UseButtomImportReturnType {
  if (!getCurrentInstance()) {
    throw new Error('useButtomImport() can only be used inside setup() or functional components!');
  }
  const BImport = ref<Nullable<ButtomImportInstance>>(null);
  const loaded = ref(false);

  function register(instance: ButtomImportInstance) {
    if (unref(loaded) && isProdMode()) {
      return;
    }
    BImport.value = instance;
    props && instance.setButtomImportProps(props);
    loaded.value = true;
  }

  const methods: ButtomImportInstance = {
    setButtomImportProps: (BImportProps: Partial<ButtomImportProps>): void => {
      unref(BImport)?.setButtomImportProps(BImportProps);
    },
    async importFile() {
      unref(BImport)?.importFile();
    },
  };

  return [register, methods];
}
